<?php
namespace app\common\model;



use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class UserMasterBlackModel extends BaseModel
{

    protected $table = 'users_master_black';

    public static function getMasters($user_id)
    {
        if(empty($user_id)){
            return [];
        }

        return self::where(['uid'=>$user_id])->whereNotNull('handle_time')->column('mid');
    }

    /**
     * 页面数据
     * @param array $input_data 图片类型
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data = [])
    {
        $limit = $input_data['limit']??null;
        $where=[];

        if(isset($input_data['check_uid'])){
            $where[] = ['users_master_black_model.uid','=',$input_data['check_uid']];
        }


        $order = 'handle_time desc';
        return self::withJoin('linkMaster','left')
            ->whereNotNull('handle_time')->whereNull('linkMaster.delete_time')->where($where)->order($order)
            ->paginate($limit);
    }

    public static function createBlack(UserModel $user_model, array $input_data = [])
    {
        $id = $input_data['id']??0;
        if(empty($id)) throw new \Exception("参数异常:id");
        $model_master = MasterModel::find($id);
        if(empty($model_master)) throw new \Exception("信息不存在或已被删除");
        $where = [
            'uid'=>$user_model['id'],
            'mid'=>$id,
        ];
        $model = self::where($where)->findOrEmpty();
        if($model->isEmpty()){
            $model->setAttrs($where);
        }
        $state = 1;
        if(empty($model['handle_time'])){
            $model->setAttr('handle_time',date('Y-m-d H:i:s'));
        }else{
            $state = 0;
            $model->setAttr('handle_time',null);
        }
        $model->save();


        return $state;

    }

    public static function removeBlock(UserModel $user_model,array $input_data = [])
    {
        $master_id = $input_data['master_id']??0;
        if(empty($master_id)) throw new \Exception("参数异常:master_id");
        self::where(['uid'=>$user_model['id'],'mid'=>$master_id])->update([
            'handle_time'=>null
        ]);
    }



    public function apiNormalInfo()
    {
        $linkMaster = $this->getRelation('linkMaster');
        return array_merge([
            'add_id'=>$this['id'],
        ],empty($linkMaster)?[]:$linkMaster->apiNormalInfo());
    }


    public function linkMaster()
    {
        return $this->belongsTo(MasterModel::class,'mid');
    }



}